/**
* 系统管理 用户管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="" v-for="(filter, index) in formInline.filters" :key="index">
        <el-input size="small" v-model="filter.fieldValue" v-bind:fieldName="filter.fieldName"
                  v-bind:fieldValue="filter.fieldValue" v-bind:compare="filter.compare"
                  @keyup.enter.native="search"
                  :placeholder="filter.placeholder" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
        <el-button size="small" type="primary" @click="handleunit()">部门设置</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" @selection-change="selectChange" :data="userData" highlight-current-row v-loading="loading"
              border element-loading-text="拼命加载中" style="width: 100%;"
              :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column align="center" prop="company" label="公司" width="150">
      </el-table-column>
      <el-table-column align="center" prop="loginName" label="用户名" width="120">
      </el-table-column>
      <el-table-column align="center" prop="userName" label="姓名" width="120">
      </el-table-column>
      <el-table-column align="center" prop="phonenumber" label="手机号" width="120">
      </el-table-column>
      <el-table-column align="center" prop="sex" label="性别" min-width="50">
        <template slot-scope="scope">
          <span>{{scope.row.sex | handleSex}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="email" label="邮件" min-width="120">
      </el-table-column>
      <el-table-column align="center" prop="roleName" label="角色" min-width="100" :formatter="roleFomatter">
      </el-table-column>
      <el-table-column align="center" prop="vos" label="VOS账户" min-width="100">
      </el-table-column>
      <el-table-column align="center" prop="status" label="状态" min-width="50">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.valid===1" active-color="#13ce66" inactive-color="#ff4949"
                     @change="editType(scope.$index, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :icon="'el-icon-video-camera-solid'"
                                @click.native="handleEdit(scope.$index, scope.row)">编辑
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-video-play'"
                                @click.native="deleteUser(scope.$index, scope.row)">删除
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-video-pause'"
                                @click.native="resetpwd(scope.$index, scope.row)">重置密码
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-circle-close'"
                                @click.native="offlineUser(scope.$index, scope.row)">下线
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"/>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
        <el-form-item label="用户名" prop="userName">
          <el-input size="small" v-model="editForm.userName" auto-complete="off" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="登录名称" prop="loginName">
          <el-input size="small" v-model="editForm.loginName" auto-complete="off" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="角色" prop="roleName">
          <el-select size="small" v-model="editForm.roleName" placeholder="请选择" class="userRole">
            <el-option :label="item.remark" :value="item.roleName" v-for="(item, index) in roles" :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input size="small" v-model="editForm.phonenumber" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input size="small" v-model="editForm.email" placeholder="请输入邮箱地址"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="editForm.sex" label="1">男</el-radio>
          <el-radio v-model="editForm.sex" label="0">女</el-radio>
        </el-form-item>
        <el-form-item label="公司" prop="email">
          <el-input size="small" disabled v-model="editForm.company" placeholder="请输入公司名称"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="addFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="addForm" :model="addForm" :rules="rules">
        <el-form-item label="用户名" prop="userName">
          <el-input size="small" v-model="addForm.userName" auto-complete="off" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input size="small" v-model="addForm.password" auto-complete="off" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="登录名称" prop="loginName">
          <el-input size="small" v-model="addForm.loginName" auto-complete="off" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="角色" prop="roleName">
          <el-select size="small" v-model="addForm.roleName" placeholder="请选择" class="userRole">
            <el-option :label="item.remark" :value="item.roleName" v-for="(item, index) in roles" :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input size="small" v-model="addForm.phonenumber" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input size="small" v-model="addForm.email" placeholder="请输入邮箱地址"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="addForm.sex" label="1">男</el-radio>
          <el-radio v-model="addForm.sex" label="0">女</el-radio>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("add")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('addForm')">保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 所属单位 -->
    <el-dialog title="所属单位" :visible.sync="unitAccessshow" width="30%" @click='closeDialog("unit")'>
      <el-tree ref="tree" default-expand-all="" :data="UserDept" :props="defaultProps" @check-change="handleClick"
               :default-checked-keys="checkmenu" node-key="id" show-checkbox check-strictly>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("unit")'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // 导入请求方法
  import {
    deptList,
    roleList,
    UserChangeDept,
    userDelete,
    UserDeptSave,
    UserDeptTree,
    userExpireToken,
    userList,
    userLock,
    userPwd,
    userSave,
    userUpdate
  } from '../../api/userMG'
  import Pagination from '../../components/Pagination'

  export default {
    data() {
      return {
        nshow: true, //switch开启
        fshow: false, //switch关闭
        loading: false, //是显示加载
        title: '添加用户',
        editFormVisible: false, //控制编辑页面显示与隐藏
        addFormVisible: false, //控制新增页面显示与隐藏
        dataAccessshow: false, //控制数据权限显示与隐藏
        unitAccessshow: false, //控制所属单位隐藏与显示
        // 编辑与添加
        editForm: {
          userId: '',
          userName: '',
          loginName: '',
          roleName: '',
          phonenumber: '',
          email: '',
          sex: '',
          company: '',
          token: localStorage.getItem('x-token')
        },
        addForm: {
          userId: '',
          userName: '',
          password: '',
          loginName: '',
          roleName: '',
          phonenumber: '',
          email: '',
          sex: '',
          token: localStorage.getItem('x-token')
        },
        // 部门参数
        unitparm: {
          userIds: '',
        },
        // 选择数据
        selectdata: [],
        selectedItem: null,
        // rules表单验证
        rules: {
          userName: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          userRealName: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
          roleName: [{required: true, message: '请选择角色', trigger: 'blur'}],
          userMobile: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {
              pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
              required: true,
              message: '请输入正确的手机号',
              trigger: 'blur'
            }
          ],
          userEmail: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {
              pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
              required: true,
              message: '请输入正确的邮箱',
              trigger: 'blur'
            }
          ],
          userSex: [{required: true, message: '请选择性别', trigger: 'blur'}]
        },
        // 删除用户
        seletedata: {
          ids: '',
          token: localStorage.getItem('logintoken')
        },
        // 重置密码
        resetpsd: {
          userId: '',
          token: localStorage.getItem('logintoken')
        },
        // 用户下线
        offline: {
          token: localStorage.getItem('logintoken')
        },
        // 请求数据参数
        formInline: {
          page: 1,
          perPage: 10,
          filters: [
            {placeholder: "请输入登录名", fieldName: "loginName", compare: "like", fieldValue: ""},
            {placeholder: "请输入用户名", fieldName: "userName", compare: "like", fieldValue: ""}
          ],
          isLock: ''
        },
        //用户数据
        userData: [],
        // 数据权限
        UserDept: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        // 选中
        checkmenu: [],
        //参数role
        saveroleId: '',
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        roles: []
      }
    },
    // 注册组件
    components: {
      Pagination
    },

    /**
     * 数据发生改变
     */
    watch: {},

    /**
     * 创建完毕
     */
    created() {
      this.getdata(this.formInline);
      this.getAllRoleList();
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // row角色转换
      roleFomatter(row) {
        for (const role of this.roles) {
          if (role.roleName === row.roleName) {
            return role.remark;
          }
        }
      },
      getAllRoleList() {
        roleList({
          "page": 1,
          "perPage": 100,
          "filters": [],
          "isLock": ""
        })
          .then(
            resp => {
              this.roles = resp.data.list;
            }
          ).catch(err => {
          this.$message.error('角色列表获取失败！')
        })
      },
      // 获取数据方法
      getdata(parameter) {
        this.loading = true;
        userList(parameter)
          .then(res => {
            if (res.success) {
              if (res.data) {
                this.pageparm.currentPage = res.data.pageNum;
                this.pageparm.pageSize = res.data.pageSize;
                this.pageparm.total = res.data.total;
                this.userData = res.data.list;
              }
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
          .catch(err => {
            this.loading = false;
            this.$message.error('刷新失败，请稍后再试！')
          });
        this.loading = false

      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage;
        this.formInline.perPage = parm.pageSize;
        this.getdata(this.formInline)
      },
      //搜索事件
      search() {
        this.getdata(this.formInline)
      },
      // 修改type
      editType: function (index, row) {
        if (row.userId === 1) {
          this.$message.error('超级管理员不能修改');
          return;
        }
        this.loading = true;
        let parm = {
          valid: row.valid === 1 ? 0 : 1,
          userId: row.userId,
        };
        // 修改状态
        userLock(parm).then(res => {
          this.loading = false;
          if (res.success) {
            this.$message({
              type: 'success',
              message: '状态修改成功'
            });
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
          this.getdata(this.formInline)
        })
      },
      //显示编辑界面
      handleEdit: function (index, row) {

        if (row.userId === 1) {
          this.$message.error('超级管理员不能修改');
          return;
        }
        this.getAllRoleList();
        this.editFormVisible = true;
        this.title = '修改用户';
        this.editForm.userId = row.userId;
        this.editForm.userName = row.userName;
        this.editForm.loginName = row.loginName;
        this.editForm.roleName = row.roleName;
        this.editForm.phonenumber = row.phonenumber;
        this.editForm.email = row.email;
        this.editForm.sex = row.sex;
        this.editForm.company = row.company;
        this.editForm.status = row.status.code;
      },
      //显示编辑界面
      handleAdd: function (index, row) {
        this.addFormVisible = true;
        this.title = '添加用户';
        this.editForm.userId = '';
        this.editForm.userName = '';
        this.editForm.loginName = '';
        this.editForm.roleName = '';
        this.editForm.phonenumber = '';
        this.editForm.email = '';
        this.editForm.sex = '';
        this.editForm.password = '';
      },
      // 编辑、添加提交方法
      submitForm(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            // 请求方法
            if (editData === 'addForm') {
              userSave(this.addForm)
                .then(res => {
                  this.editFormVisible = false;
                  this.loading = false;
                  if (res.success) {
                    this.getdata(this.formInline);
                    this.$message({
                      type: 'success',
                      message: '数据保存成功！'
                    })
                  } else {
                    this.$message({
                      type: 'info',
                      message: res.msg
                    })
                  }
                })
                .catch(err => {
                  console.error(err);
                  this.editFormVisible = false;
                  this.loading = false;
                  this.$message.error('保存失败，请稍后再试！')
                })
            } else if (editData === 'editForm') {
              userUpdate(this.editForm)
                .then(res => {
                  this.editFormVisible = false;
                  this.loading = false;
                  if (res.success) {
                    this.getdata(this.formInline);
                    this.$message({
                      type: 'success',
                      message: '数据保存成功！'
                    })
                  } else {
                    this.$message({
                      type: 'info',
                      message: res.msg
                    })
                  }
                })
                .catch(err => {
                  this.editFormVisible = false;
                  this.loading = false;
                  this.$message.error('保存失败，请稍后再试！')
                })
            }

          } else {
            return false
          }
        })
      },
      // 显示部门设置
      handleunit: function (index, row) {
        console.log(this.selectdata)
        if(!this.selectdata || this.selectdata.length !== 1) {
          this.$message({
            type: 'error',
            message: "请选择一个用户"
          })
          return;
        }
        this.unitAccessshow = true;
        deptList({
          page: 1,
          perPage: 100,
          filters: []
        })
          .then(res => {
            if (res.success) {
              this.UserDept = this.changeArr(res.data.list);
              console.log(res);
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
          .catch(err => {
            console.error(err);
            this.loading = false;
            this.$message.error('配置权限失败,请稍后再试！')
          })
      },
      handleClick(data, checked, node) {
        if (checked) {
          this.$refs.tree.setCheckedNodes([]);
          this.$refs.tree.setCheckedNodes([data]);
          this.unitparm.companyId = data.id;
          this.unitparm.company = data.name;
          //交叉点击节点
          this.unitPermSave();
        } else {
        }
      },
      // 保存部门
      unitPermSave() {
        let len = this.selectdata;
        let ids = [];
        if (len !== 0) {
          for (let i = 0; i < len.length; i++) {
            ids.push(len[i].userId)
          }
        }
        this.unitparm.userIds = ids.join(',');
        UserChangeDept(this.unitparm)
          .then(res => {
            this.unitAccessshow = false;
            if (res.success) {
              this.$message({
                type: 'success',
                message: '部门设置成功！'
              });
              this.getdata(this.formInline)
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
          .catch(err => {
            this.loading = false;
            this.$message.error('部门设置失败,请稍后再试！')
          })
      },
      // 选择复选框事件
      selectChange(val) {
        this.selectdata = val
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog === 'edit') {
          this.editFormVisible = false
        } else if (dialog === 'perm') {
          this.dataAccessshow = false
        } else if (dialog === 'unit') {
          this.unitAccessshow = false
        }
      },
      // 删除用户
      deleteUser(index, row) {
        if (row.userId === 1) {
          this.$message.error('超级管理员不能修改');
          return;
        }
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            // 删除
            userDelete(row.userId)
              .then(res => {
                if (res.success) {
                  this.$message({
                    type: 'success',
                    message: '数据已删除!'
                  });
                  this.getdata(this.formInline)
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error('数据删除失败，请稍后再试！')
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除！'
            })
          })
      },
      // 重置密码
      resetpwd(index, row) {
        if (row.userId === 1) {
          this.$message.error('超级管理员不能修改');
          return;
        }
        this.$confirm('确定要重置密码吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            userPwd({userId: row.userId})
              .then(res => {
                if (res.success) {
                  this.$message({
                    type: 'success',
                    message: '重置密码成功！'
                  });
                  this.getdata(this.formInline)
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.loading = false;
                this.$message.error('重置密码失败，请稍后再试！')
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '取消重置密码！'
            })
          })
      },
      // 数据权限
      dataAccess: function (index, row) {
        this.dataAccessshow = true;
        this.saveroleId = row.userId;
        UserDeptTree(row.userId)
          .then(res => {
            if (res.data.success) {
              this.checkmenu = this.changemenu(res.data.data)
              this.UserDept = this.changeArr(res.data.data)
            } else {
              this.$message({
                type: 'info',
                message: res.data.msg
              })
            }
          })
          .catch(err => {
            this.loading = false;
            this.$message.error('获取权限失败，请稍后再试！')
          })
      },
      //数据格式化
      changeArr(data) {
        const tree = [];
        for (let i = 0; i < data.length; i++) {
          let datum = data[i];
          let tm = {
            id: datum.id,
            name: datum.name,
            checked: false
          };
          for (let j = 0; j < this.selectdata.length; j++) {
            let d = this.selectdata[j];
            if (d.companyId === datum.id) {
              tm.checked = false;
            }
          }
          tree.push(tm);
        }
        return tree
      },
      // 选中菜单
      changemenu(arr) {
        let change = [];
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].checked) {
            change.push(arr[i].id)
          }
        }
        return change
      },
      // 菜单权限-保存
      menuPermSave() {
        let parm = {
          userId: this.saveroleId,
          deptIds: ''
        };
        let node = this.$refs.tree.getCheckedNodes();
        let moduleIds = [];
        if (node.length !== 0) {
          for (let i = 0; i < node.length; i++) {
            moduleIds.push(node[i].id)
          }
          parm.deptIds = JSON.stringify(moduleIds)
        }
        UserDeptSave(parm)
          .then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: '权限保存成功'
              });
              this.dataAccessshow = false;
              this.getdata(this.formInline)
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
          .catch(err => {
            console.error(err);
            this.loading = false;
            this.$message.error('权限保存失败，请稍后再试！')
          })
      },
      // 下线用户
      offlineUser(index, row) {
        if (row.userId === 1) {
          this.$message.error('超级管理员不能修改');
          return;
        }
        this.$confirm('确定要让' + row.userName + '用户下线吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            userExpireToken(row.userName)
              .then(res => {
                if (res.success) {
                  this.$message({
                    type: 'success',
                    message: '用户' + row.userName + '强制下线成功！'
                  });
                  this.getdata(this.formInline)
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.loading = false;
                this.$message.error('用户下线失败，请稍后再试！')
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }
</style>

